<template>
  <view class="container">
    <image :src="imagePath" mode="widthFix" v-if="imagePath" class="display-image"></image>
    <view class="loading" v-else>图片加载中...</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imagePath: '' // 存储下载后的图片本地路径
    };
  },
  onLoad() {
    this.downloadImage();
  },
  methods: {
    downloadImage() {
      const imageUrl = "https://cdn.pixabay.com/photo/2025/11/05/20/57/monastery-9939590_1280.jpg";
      uni.downloadFile({
        url: imageUrl,
        // 监听下载进度
        onProgressUpdate: (res) => {
          console.log('下载进度：' + res.progress + '%');
          console.log('已下载字节数：' + res.totalBytesWritten);
          console.log('总字节数：' + res.totalBytesExpectedToWrite);
        },
        success: (res) => {
          if (res.statusCode === 200) {
            this.imagePath = res.tempFilePath; // 赋值本地路径以显示图片
            console.log('图片下载成功，本地路径：' + res.tempFilePath);
          }
        },
        fail: (err) => {
          console.error('图片下载失败：', err);
        }
      });
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20rpx;
}
.display-image {
  width: 100%;
  border-radius: 8rpx;
}
.loading {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
}
</style>